//
//  NSString+EnDeCoding.m
//  MFWSdk
//
//  Created by Song Xiaofeng on 13-7-26.
//  Copyright (c) 2013年 Mafengwo Inc. All rights reserved.
//

#import "NSString+EnDeCoding.h"
#import "Base64.h"
#import <CommonCrypto/CommonDigest.h>
#import "LoadableCategory.h"

MAKE_CATEGORIES_LOADABLE(MFWSdk_NSString_EnDeCoding)

@implementation NSString (EnDeCoding)

- (NSString*)urlEncode
{
    return [self stringByEscapingForURLArgument];
}

- (NSString*)urlDecode;
{
    return [self stringByUnescapingFromURLArgument];
}

- (NSString*)stringByEscapingForURLArgument;
{
    // Encode all the reserved characters, per RFC 3986
    // (<http://www.ietf.org/rfc/rfc3986.txt>)
    CFStringRef escaped =
    CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                            (CFStringRef)self,
                                            NULL,
                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                            kCFStringEncodingUTF8);
    NSString *res = [NSString stringWithString:(__bridge NSString *)(escaped)];
    CFRelease(escaped);
    return res;
}

- (NSString*)stringByUnescapingFromURLArgument;
{
    NSMutableString *resultString = [NSMutableString stringWithString:self];
    [resultString replaceOccurrencesOfString:@"+"
                                  withString:@" "
                                     options:NSLiteralSearch
                                       range:NSMakeRange(0, [resultString length])];
    return [resultString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (NSString*)base64Encode;
{
    return [Base64 stringByEncodingData:[self dataUsingEncoding:NSUTF8StringEncoding]];
}

- (NSString*)base64Decode;
{
    return [[NSString alloc] initWithData:[Base64 decodeString:self] encoding:NSUTF8StringEncoding];
}

- (NSString*)md5Encode;
{
    return [[self MD5Encode] lowercaseString];
}

- (NSString*)MD5Encode;
{
    const char * pointer = [self UTF8String];
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(pointer, (CC_LONG)strlen(pointer), md5Buffer);
    
    NSMutableString *string = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [string appendFormat:@"%02x",md5Buffer[i]];
    
    return string;
}
@end
